package com.example.signsystem.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qcby.framework.common.pojo.PageResult;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 分页工具类
 *
 * @author yunyan
 * @date 2023/7/11
 */
public class PageResultFactory {

    public PageResultFactory(){
    }

    public static <E> PageResult<E> createPageResult(IPage<E> page){
        PageResult pageResult=new PageResult<>();
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    public static <R,E> PageResult<R> createPageResult(IPage<E> page,Class<R> rClass){
        PageResult pageResult=new PageResult<>();
        pageResult.setList((List)page.getRecords().stream().map((e) -> {
            R r = ReflectUtil.newInstanceIfPossible(rClass);
            BeanUtil.copyProperties(e, r, new String[0]);
            return r;
        }).collect(Collectors.toList()));
            pageResult.setTotal(Convert.toLong(page.getTotal()));
            return pageResult;
    }

    public static <R,E> PageResult<R> createPageResult(PageResult<E> page,Class<R> rClass) {
        PageResult<R> pageResult = new PageResult<R>();
        pageResult.setList(page.getList().stream().map((e) -> {
            R r = ReflectUtil.newInstanceIfPossible(rClass);
            BeanUtil.copyProperties(e, r, new String[0]);
            return r;
        }).collect(Collectors.toList()));
        pageResult.setTotal(Convert.toLong(page.getTotal()));
        return pageResult;
    }
}
